import { lazyBatchReport } from '../report/index'

export const originalProto = XMLHttpRequest.prototype
export const originalSend = originalProto.send
export const originalOpen = originalProto.open

export default function xhr() {
  originalProto.open = function (...args) {
    this.url = args[1]
    this.method = args[0]

    originalOpen.apply(this, args)
  }

  originalProto.send = function (...args) {
    this.startTIme = Date.now()

    const onLoaded = () => {
      this.endTime = Date.now()
      this.duration = this.endTime - this.startTIme

      const { url, method, startTIme, endTime, duration, status } = this

      const reportDaa = {
        status,
        url,
        method: method.toUpperCase(),
        startTIme,
        endTime,
        duration,
        type: 'performance',
        subType: 'xhr',
        success: status >= 200 && status < 300,
      }

      // 数据上报
      lazyBatchReport(reportData)

      this.removeEventListener('loadend', onLoaded, true) // 移除监听：loadend事件总数在一个资源的加载进度停止之后被触发
    }

    this.addEventListener('loadend', onLoaded, true)

    originalSend.apply(this, args)
  }
}
